package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.constant.IpAddressConstant;
import com.ruoyi.system.domain.ERP.MaterialDataErp;
import com.ruoyi.system.domain.ERP.MaterialTypeErp;
import com.ruoyi.system.domain.ERP.MesOperationsErpDTO;
import com.ruoyi.system.domain.base.BaseMaterial;
import com.ruoyi.system.domain.base.MesOperations;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IBaseMaterialService;
import com.ruoyi.system.utils.InterfaceLogUtil.InterfaceLogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物料信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-01
 */
@Service
@Component("erpWlTask")
public class BaseMaterialServiceImpl extends ServiceImpl<BaseMaterialMapper, BaseMaterial> implements IBaseMaterialService {

    @Autowired
    private InterfaceLogMapper interfaceLogMapper;
    @Autowired
    private MaterialTypeErpMapper materialTypeErpMapper;
    @Autowired
    private MaterialDataErpMapper materialDataErpMapper;
    @Autowired
    private InterfaceLogUtil interfaceLogUtil;
    @Autowired
    private MesOperationsMapper mesOperationsMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String material() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("checkFlag", IpAddressConstant.ERP_CHECK_FLAG);
        String res = HttpUtil.get(IpAddressConstant.ERP_IP + "/basic/inventory/syncErpInventoryList", paramMap);
        Map map = JSONUtil.toBean(res, Map.class);
        List data = (List) map.get("data");
        String codestr = (String) map.get("code");

        if (IterUtil.isNotEmpty(data) && "10000".equals(codestr)) {
            JSONArray array = JSONUtil.parseArray(JSONUtil.toJsonStr(map.get("data")));
            List<MaterialDataErp> maList = JSONUtil.toList(array, MaterialDataErp.class);
            //进行物料主类型新增
            maList.stream().forEach(i -> {
                materialDataErpMapper.insert(i);
            });


            //同步成功之后进行回调
//            HashMap<String, Object> paramMapRes = new HashMap<>();
//            List<String> pks = maList.stream().map(i -> i.getInvCode()).collect(Collectors.toList());
//            paramMapRes.put("codes", pks);
//            paramMapRes.put("checkFlag", IpAddressConstant.ERP_CHECK_FLAG);
//            String resp= HttpUtil.post(IpAddressConstant.ERP_IP+"/basic/inventory/syncStateUpdate", JSONUtil.toJsonStr(paramMapRes));
//            Map mapResp = JSONUtil.toBean(resp, Map.class);
//            String code = (String)mapResp.get("code");
//
//
//            if(!"10000".equals(code)){
//                throw new CustomException("物料主数据同步失败");
//            }

        }
        return "同步成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String materialSync(List<MaterialDataErp> list) {

        Date startDate = new Date();

        if (IterUtil.isEmpty(list)) {
            throw new CustomException("同步数据不能为空");
        }

        //判断物料编码不为空
        list.stream().forEach(i -> {
            if(StrUtil.isBlank(i.getInvCode())){
                throw new CustomException("物料编码不能为空");
            }
        });

        list.stream().forEach(i -> {
            MaterialDataErp ma = materialDataErpMapper.selectOne(new QueryWrapper<MaterialDataErp>().eq("inv_code", i.getInvCode()));
            if (ObjectUtil.isNotNull(ma)) {
                materialDataErpMapper.update(i, new QueryWrapper<MaterialDataErp>().eq("inv_code", i.getInvCode()));
            } else {
                //默认不删除
                i.setIsDelete(0);
                materialDataErpMapper.insert(i);
            }
        });

        //日志记录
        interfaceLogUtil.insertLog(JSONUtil.toJsonStr(list),
                startDate, new Date(), InterfaceLogUtil.DIR_MOM_SAP,
                InterfaceLogUtil.TYPE_HTTP,
                "物料主数据同步成功",
                InterfaceLogUtil.INTERFACENAME_WLTB
        );

        return "同步成功";
    }

    @Override
    public String materialDeleteSync(List<String> list) {

        Date startDate = new Date();

        if (IterUtil.isEmpty(list)) {
            throw new CustomException("同步数据不能为空");
        }

        list.stream().forEach(i -> {
            MaterialDataErp ma = materialDataErpMapper.selectOne(new QueryWrapper<MaterialDataErp>().eq("inv_code", i));
            if (ObjectUtil.isNull(ma)) {
                throw new CustomException("此物料编码不存在，无法进行删除！");
            }
            ma.setIsDelete(1);
            materialDataErpMapper.update(ma, new QueryWrapper<MaterialDataErp>().eq("inv_code", i));
        });

        //日志记录
        interfaceLogUtil.insertLog(JSONUtil.toJsonStr(list),
                startDate, new Date(), InterfaceLogUtil.DIR_ERP_MOM,
                InterfaceLogUtil.TYPE_HTTP,
                "物料主数据删除同步成功",
                InterfaceLogUtil.INTERFACENAME_WLSCTB
        );

        return "同步成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String mesopSync(List<MesOperationsErpDTO> list) {

        Date startDate = new Date();

        if (IterUtil.isEmpty(list)) {
            throw new CustomException("工艺数据不能为空");
        }
        list.stream().forEach(i -> {

            List<MesOperations> operations = mesOperationsMapper.selectList(new QueryWrapper<MesOperations>().eq("product_code", i.getProductCode()));
            if (IterUtil.isEmpty(operations)) {
                operations.stream().forEach(j -> {
                    MesOperations mesOperations = new MesOperations();
                    mesOperations.setStatus("0");//将之前版本设置为失效
                    mesOperationsMapper.update(mesOperations, new QueryWrapper<MesOperations>().eq("product_code", j.getProductCode()));
                });
            }

            MesOperations op = mesOperationsMapper.selectOne(new QueryWrapper<MesOperations>().eq("operation_code", i.getOperationCode()).eq("product_code", i.getProductCode()));
            if (ObjectUtil.isNotNull(op)) {
                MesOperations mesOperations = new MesOperations();
                BeanUtil.copyProperties(i, mesOperations);
                mesOperations.setRoutingCode(mesOperations.getOperErpId());
                mesOperations.setOperationCode(mesOperations.getOperErpCode());
                mesOperationsMapper.update(mesOperations, new QueryWrapper<MesOperations>().eq("operation_code", i.getOperationCode()));
            } else {
                MesOperations mesOperations = new MesOperations();
                BeanUtil.copyProperties(i, mesOperations);
                mesOperations.setRoutingCode(mesOperations.getOperErpId());
                mesOperations.setOperationCode(mesOperations.getOperationCode());
                mesOperationsMapper.insert(mesOperations);
            }

        });

        //日志记录
        interfaceLogUtil.insertLog(JSONUtil.toJsonStr(list),
                startDate, new Date(), InterfaceLogUtil.DIR_ERP_MOM,
                InterfaceLogUtil.TYPE_HTTP,
                "ERP工艺数据接收成功",
                InterfaceLogUtil.INTERFACENAME_GYTB
        );

        return "同步成功";
    }

    @Override
    public String materialTypeSync() {

        Date startDate = new Date();

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("checkFlag", IpAddressConstant.ERP_CHECK_FLAG);
        String res = HttpUtil.get(IpAddressConstant.ERP_IP + "/basic/inventoryClass/syncInventoryClassList", paramMap);
        Map map = JSONUtil.toBean(res, Map.class);
        List data = (List) map.get("data");
        String codestr = (String) map.get("code");

        //日志记录
        interfaceLogUtil.insertLog(JSONUtil.toJsonStr(paramMap),
                startDate, new Date(), InterfaceLogUtil.DIR_MOM_ERP,
                InterfaceLogUtil.TYPE_HTTP,
                "物料主类型同步成功",
                InterfaceLogUtil.INTERFACENAME_WLLXTB
        );

        if (IterUtil.isNotEmpty(data) && "10000".equals(codestr)) {
            JSONArray array = JSONUtil.parseArray(JSONUtil.toJsonStr(map.get("data")));
            List<MaterialTypeErp> maList = JSONUtil.toList(array, MaterialTypeErp.class);
            //进行物料主类型新增
            maList.stream().forEach(i -> {
                materialTypeErpMapper.insert(i);
            });


            //同步成功之后进行回调
            HashMap<String, Object> paramMapRes = new HashMap<>();
            List<String> pks = maList.stream().map(i -> i.getInvClassCode()).collect(Collectors.toList());
            paramMapRes.put("codes", pks);
            paramMapRes.put("checkFlag", IpAddressConstant.ERP_CHECK_FLAG);
            String resp = HttpUtil.post(IpAddressConstant.ERP_IP + "/basic/inventoryClass/syncStateUpdate", JSONUtil.toJsonStr(paramMapRes));
            Map mapResp = JSONUtil.toBean(resp, Map.class);
            String code = (String) mapResp.get("code");


            interfaceLogUtil.insertLog(JSONUtil.toJsonStr(paramMapRes),
                    startDate, new Date(), InterfaceLogUtil.DIR_MOM_ERP,
                    InterfaceLogUtil.TYPE_HTTP,
                    "物料主类型回调同步成功",
                    InterfaceLogUtil.INTERFACENAME_WLLXHDTB
            );

            if (!"10000".equals(code)) {
                throw new CustomException("物料主类型同步失败");
            }

        }
        return "同步成功";
    }


}
